import { ref, onUnmounted } from 'vue'

export function useWebSocket(url) {
  const ws = ref(null)
  const isConnected = ref(false)
  const messages = ref([])
  const users = ref([])
  const reconnectAttempts = ref(0)
  const maxReconnectAttempts = 5

  let reconnectTimer = null

  const connect = (username, userId) => {
    try {
      const wsUrl = `${url}?username=${encodeURIComponent(username)}&userId=${userId}`
      ws.value = new WebSocket(wsUrl)

      ws.value.onopen = () => {
        console.log('WebSocket 连接成功')
        isConnected.value = true
        reconnectAttempts.value = 0
      }

      ws.value.onmessage = (event) => {
        try {
          const data = JSON.parse(event.data)
          handleMessage(data)
        } catch (error) {
          console.error('解析消息失败:', error)
        }
      }

      ws.value.onerror = (error) => {
        console.error('WebSocket 错误:', error)
      }

      ws.value.onclose = () => {
        console.log('WebSocket 连接关闭')
        isConnected.value = false
        attemptReconnect(username, userId)
      }
    } catch (error) {
      console.error('连接 WebSocket 失败:', error)
    }
  }

  const attemptReconnect = (username, userId) => {
    if (reconnectAttempts.value < maxReconnectAttempts) {
      reconnectAttempts.value++
      console.log(`尝试重新连接... (${reconnectAttempts.value}/${maxReconnectAttempts})`)

      reconnectTimer = setTimeout(() => {
        connect(username, userId)
      }, 3000)
    } else {
      console.error('达到最大重连次数，停止重连')
    }
  }

  const handleMessage = (data) => {
    console.log('收到消息:', data)

    switch (data.type) {
      case 'join':
        messages.value.push({
          type: 'system',
          content: `${data.username} 加入了聊天室`,
          timestamp: data.timestamp,
        })
        break

      case 'leave':
        messages.value.push({
          type: 'system',
          content: `${data.username} 离开了聊天室`,
          timestamp: data.timestamp,
        })
        break

      case 'message':
        messages.value.push({
          type: 'message',
          userId: data.userId,
          username: data.username,
          content: data.content,
          timestamp: data.timestamp,
        })
        console.log('消息已添加，当前消息数:', messages.value.length)
        break

      case 'user_list':
        users.value = data.data || []
        console.log('用户列表已更新:', users.value)
        break

      default:
        console.log('未知消息类型:', data.type, data)
    }
  }

  const sendMessage = (content) => {
    if (ws.value && isConnected.value && content.trim()) {
      const message = {
        type: 'message',
        content: content.trim(),
      }
      ws.value.send(JSON.stringify(message))
    }
  }

  const disconnect = () => {
    if (reconnectTimer) {
      clearTimeout(reconnectTimer)
      reconnectTimer = null
    }
    if (ws.value) {
      ws.value.close()
      ws.value = null
    }
    isConnected.value = false
  }

  onUnmounted(() => {
    disconnect()
  })

  return {
    isConnected,
    messages,
    users,
    connect,
    disconnect,
    sendMessage,
  }
}
